package cn.e3mall.controller;

import cn.e3mall.common.utils.FastDFSClient;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping(value = "/pic")
public class PicController {

    private static final Logger LOG = LoggerFactory.getLogger(PicController.class);

    @Value("${imageServer_url}")
    private String imageServerUrl;

    @RequestMapping(value = "/upload")
    public String uploadFile(MultipartFile uploadFile) {
        //上传
        Map<String,Object> map = new HashMap<>(  );
        try {
            FastDFSClient fastDFSClient = new FastDFSClient( "classpath:conf/fastdfs.conf" );
            String originalFilename = uploadFile.getOriginalFilename();
            String extName = originalFilename.substring( originalFilename.lastIndexOf( "." ) + 1 );
            //返回地址
            String fileUrl = fastDFSClient.uploadFile( uploadFile.getBytes(), extName );
            //补充url
            fileUrl=imageServerUrl+fileUrl;
            LOG.info( "图片地址{}",fileUrl);
            map.put( "error",0);
            map.put( "url",fileUrl );
        } catch (Exception e) {
            LOG.error( "上传出错了" );
            map.put( "error",1);
            map.put( "message","上传失败" );
        }
        String s = JSONObject.toJSONString( map );
     return s;
    }

}
